define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/person/index' + location.search,
                    add_url: 'pt/person/add',
                    edit_url: 'pt/person/edit',
                    // del_url: 'pt/person/del',
                    multi_url: 'pt/person/multi',
                    import_url: 'pt/person/import',
                    table: 'pt_person',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        // {field: 'user_id', title: __('User_id')},
                        {field: 'user_name', title: __('User_name'), operate: 'LIKE'},
                        {field: 'sex', title: __('Sex'), searchList: {"0":__('Sex 0'),"1":__('Sex 1'),"2":__('Sex 2')}, formatter: Table.api.formatter.normal},
                        {field: 'phone', title: __('Phone'), operate: 'LIKE'},
                        {field: 'user_type', title: __('User_type'), searchList: {"self":__('User_type self'),"intern":__('User_type intern'),"labor":__('User_type labor')}, formatter: Table.api.formatter.normal},
                        {field: 'depart.name', title: __('Pt_depart_id'), operate: false},
                        {field: 'job.name', title: __('Pt_job_id'), operate: false},
                        {field: 'labor.name', title: __('Pt_labor_id'), operate: false},
                        {field: 'user_id', title: __('关联微信号'),operate: false,
                          formatter: function(value, row, index) {
                            if (value == 0) {
                                return '<font color="red">未关联</font>';
                            }
                            return '<font color="blue">已关联</font>';
                          }
                        },
                        {field: 'confirm_idcard', title: __('实名状态'), searchList: {"0":__('未认证'),"1":__('已认证'),"2":__('认证失败')}, formatter: Table.api.formatter.status},
                        {field: 'status', title: __('Status'), searchList: {"hidden":__('Status hidden'),"normal":__('Status normal')}, formatter: Table.api.formatter.status},
                        {field: 'duty_date', title: __('Duty_date'), operate:'RANGE', addclass:'datetimerange', autocomplete:false},
                        {field: 'white_black', title: __('White_black'), searchList: {"none":__('White_black none'),"white":__('White_black white'),"black":__('White_black black')}, formatter: Table.api.formatter.normal},
                        {field: 'id_card', title: __('Idcard'), operate: 'LIKE', visible: false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        // {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate},
                        {
                          field: 'operate', 
                          title: __('Operate'), 
                          table: table, 
                          events: Table.api.events.operate, 
                          buttons: [
                              {
                                  name: 'planwork',
                                  text: __('工作安排'),
                                  icon: 'fa',
                                  classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                  url: 'pt/duty_list/work',
                                  extend: "data-area='[\"90%\", \"90%\"]'",
                              },
                              {
                                  name: 'whiteblack',
                                  text: __('黑白名单'),
                                  icon: 'fa',
                                  classname: 'btn btn-info btn-xs btn-detail btn-dialog',
                                  url: 'pt/white_black/edit'
                              },
                          ],

                          formatter: Table.api.formatter.operate

                        }
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
            });
            var commonQuery;
            table.on('common-search.bs.table', function (event, table, query) {
                //这里可以获取到普通搜索表单中字段的查询条件 query就包含filter 和 op
                console.log(query);
                commonQuery = query;
            });
            $(document).on("click", ".btn-export", function () {
                var filter = ''
                var op = ''
                if (commonQuery && commonQuery.filter !== undefined) {
                    var filters = commonQuery.filter
                    var ops = commonQuery.op
                    var getFilter = {}
                    var getOp = {}
                    for(var k in filters) {
                        if (filters[k] != '') {
                            getFilter[k] = filters[k]
                            getOp[k] = ops[k]
                        }
                    }
                    filter = JSON.stringify(getFilter)
                    op = JSON.stringify(getOp)
                }
                //获取搜索参数
                Fast.api.ajax({
                    url:'pt/person/export?filter='+encodeURIComponent(filter)+'&op='+encodeURIComponent(op)
                }, function(res){
                    console.log('export =>', res)
                    window.location.href=res['file']
                }, function(){
                    console.log('导出失败');
                    Backend.api.toastr.error('导出失败');
                });
            });
            $(document).on("click", ".btn-importperson", function () {
                Fast.api.open("pt/person/import", "导入人员信息", {
                    callback:function(value){
                      var msg = value.msg + '<br />';
                      var err = value.err;
                      for(var i in err) {
                          msg = msg + err[i] + '<br />';
                      }
                      Layer.alert(msg, {title: "导入结果提示"});
                      table.bootstrapTable('refresh')
                    }
                });
            })

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        import: function () {
            $(document).on("click", ".btn-default", function() {
                var templateFile = $("#template_file").val();
                window.open(templateFile);
            })
            $(document).on("click", ".btn-primary", function () {
                var personFile = $("#c-person_file").val();
                if (personFile == '') {
                    Backend.api.toastr.error('请选择导入的文件');
                    return
                }
                const params = Object.assign({})
                params.person_file = personFile 
                console.log('params =>', params)
                $.ajax({
                    url: `pt/person/import`,
                    type: 'post',
                    dataType: 'json',
                    data: params,
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                            if (ret.code === 1) {
                                Fast.api.close(ret.data);
                            } else {
                                Backend.api.toastr.error(ret.msg);
                            }
                        }
                    }, error: function (e) {
                        console.log(e.message)
                        Backend.api.toastr.error('导入失败');
                    }
                });
            })
            $("#faupload-person").data("upload-success", function(data, ret, up, file){
                console.log('data =>', data)
                console.log('ret =>', ret)
                console.log('up =>', up)
                console.log('file =>', file)
            });
            Controller.api.bindevent();
        },
        batch: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'pt/person/batch' + location.search,
                    // add_url: 'pt/person/add',
                    // edit_url: 'pt/person/edit',
                    // del_url: 'pt/person/del',
                    multi_url: 'pt/person/multi',
                    // import_url: 'pt/person/import',
                    table: 'pt_person',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                searchFormVisible: true,
                searchFormTemplate: 'customformtpl',
                pagination: false,
                height:600,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID'), operate: false},
                        {field: 'user_name', title: __('User_name'), operate: false},
                        {field: 'sex', title: __('Sex'), searchList: {"0":__('Sex 0'),"1":__('Sex 1'),"2":__('Sex 2')}, formatter: Table.api.formatter.normal, operate: false},
                        {field: 'phone', title: __('Phone'), operate: false},
                        {field: 'user_type', title: __('User_type'), searchList: {"self":__('User_type self'),"intern":__('User_type intern'),"labor":__('User_type labor')}, formatter: Table.api.formatter.normal, operate: false},
                        {field: 'labor.name', title: __('Pt_labor_id'), operate: false},
                        {field: 'white_black', title: __('White_black'), searchList: {"none":__('White_black none'),"white":__('White_black white'),"black":__('White_black black')}, formatter: Table.api.formatter.normal, operate: false},
                        {field: 'job_date', title: __('工作日期'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, visible: false},
                        {field: 'white_black', title: __('白名单'), searchList: {"white":__('White_black white')}, formatter: Table.api.formatter.normal, visible: false},
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
                search: false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $(document).on("click", ".btn-selected", function () {
                const selectData = Table.api.selecteddata(table); 
                const personId = []
                for(let d in selectData) {
                    personId.push(selectData[d]['id'])
                    // Layer.alert(JSON.stringify(selectData[d]));
                }
                const jobId = $('#jobId').val()
                const start = $('#start').val()
                const end = $('#end').val()
                const close = $('#close').val()
                console.log('jobId =>', jobId)
                console.log('personId =>', personId)
                const params = {
                    'start_date': start,
                    'end_date': end,
                    'job_id': jobId,
                    'person_ids': personId,
                }
                console.log('select params =>', params)
                // Layer.alert(JSON.stringify(personId));
                $.ajax({
                    url: "pt/duty_list/workBatchAdd",
                    type: 'post',
                    dataType: 'json',
                    data: params,
                    success: function (ret) {
                        if (ret.hasOwnProperty("code")) {
                            var data = ret.hasOwnProperty("data") && ret.data != "" ? ret.data : "";
                            if (ret.code === 1) {
                                Backend.api.toastr.success('岗位设置成功');
                                table.bootstrapTable('refresh');
                                if (close == '1') {
                                  Fast.api.close('ok')
                                }
                            } else {
                                Backend.api.toastr.error(ret.msg);
                            }
                        }
                    }, error: function (e) {
                        Backend.api.toastr.error(e.message);
                    }
                });
            });
        },
        viewjob: function () {
            // 初始化表格参数配置
            var jobId = $("#jobId").val();
            var date = $("#date").val();
            Table.api.init({
                extend: {
                    index_url: 'pt/person/viewjob' + location.search,
                    // add_url: 'pt/person/add',
                    // edit_url: 'pt/person/edit',
                    del_url: 'pt/person/deljob?jobId=' + jobId + '&date=' + date,
                    // multi_url: 'pt/person/multi',
                    // import_url: 'pt/person/import',
                    table: 'pt_person',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                height:600,
                pagination: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID'), operate: false},
                        {field: 'user_name', title: __('User_name'), operate: false},
                        {field: 'sex', title: __('Sex'), searchList: {"0":__('Sex 0'),"1":__('Sex 1'),"2":__('Sex 2')}, formatter: Table.api.formatter.normal, operate: false},
                        {field: 'phone', title: __('Phone'), operate: false},
                        {field: 'user_type', title: __('User_type'), searchList: {"self":__('User_type self'),"intern":__('User_type intern'),"labor":__('User_type labor')}, formatter: Table.api.formatter.normal, operate: false},
                        {field: 'labor.name', title: __('Pt_labor_id'), operate: false},
                        {field: 'operate', title: __('Operate'), table: table, events: Table.api.events.operate, formatter: Table.api.formatter.operate},
                    ]
                ],
                showToggle: false,
                showColumns: false,
                showExport: false,
                commonSearch: false,
                search: false,
            });

            // 为表格绑定事件
            Table.api.bindevent(table);

            $(document).on("click", ".btn-selected", function () {
                const jobId = $('#jobId').val()
                const date = $('#date').val()
                console.log('jobId =>', jobId)
                console.log('date =>', date)
                Fast.config.openArea = ["80%", "80%"]
                Fast.api.open("pt/person/batch?jobId=" + jobId + "&date=" + date + '&close=1', date + "岗位设置", {
                    callback:function(value){
                      table.bootstrapTable('refresh');
                      console.log('handleClick =>', value)

                    }
                });
            });
            $(document).on("click", ".btn-close", function () {
                Fast.api.close('ok')
            });

        },
        add: function () {
            $(".intern").hide();
            $(".labor").hide();
            $(".self").hide();
            var userType = $('#c-user_type').val();
            console.log('userType =>', userType)
            if (userType == 'labor') {
                $(".labor").show();
            }
            if (userType == 'self') {
                $(".self").show();
            }
            
            $("#c-user_type").on("change", function () {
                var userType = $('#c-user_type').val();
                $(".intern").hide();
                $(".labor").hide();
                $(".self").hide();
                if (userType == 'intern') {
                    $(".intern").show();
                }
                if (userType == 'labor') {
                    $(".labor").show();
                }
                if (userType == 'self') {
                    $(".self").show();
                }
            }) 
            Controller.api.bindevent();
        },
        edit: function () {
            var userType = $('#c-user_type').val();
            $(".intern").hide();
            $(".labor").hide();
            $(".self").hide();
            if (userType == 'intern') {
                $(".intern").show();
            }
            if (userType == 'labor') {
                $(".labor").show();
            }
            if (userType == 'self') {
                $(".self").show();
            }
            $("#c-user_type").on("change", function () {
                var userType = $('#c-user_type').val();
                $(".intern").hide();
                $(".labor").hide();
                $(".self").hide();
                if (userType == 'intern') {
                    $(".intern").show();
                }
                if (userType == 'labor') {
                    $(".labor").show();
                }
                if (userType == 'self') {
                    $(".self").show();
                }
            }) 
            Controller.api.bindevent();
        },
        work: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            }
        }
    };
    return Controller;
});
